import React, { Component } from 'react'
import { Form, Input, Button } from 'antd'
import { userLogin, getUserInfo } from '../api/user'
import { FilterRoutes } from '../utils'
import routes from '../router/routes'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import './Login.css'

class Login extends Component {
    onFinish = (info) => {
        const { FilterList } = this.props
        userLogin(info).then(res => {
            sessionStorage.setItem('token', res.data.token)
            // 获取用户信息
            getUserInfo().then(res => {
                const auth = res.data.data.identity_text
                // 对路由表里的数据进行筛选 ==>  返回筛选过后的数据
                let list = FilterRoutes(routes, auth)
                // 发送给redux
                FilterList(list[0].children)
                // 登录
                this.props.history.push('/home')
            })
        })
    };

    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    render() {
        return (
            <div className="h100 login">
                <div className="warp">
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        onFinish={ this.onFinish }
                        onFinishFailed={ this.onFinishFailed }
                        autoComplete="off"
                    >
                        <Form.Item
                            label="账号"
                            name="user_name"
                            rules={[{ required: true, message: '请输入账号', min: 6 }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="密码"
                            name="user_pwd"
                            rules={[{ required: true, message: '请输入密码' }]}
                        >
                            <Input.Password />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        )
    }
}

let mapState = (state) => {
    const { routes } = state
    return {
        routes
    }
}

let mapDispatch = (dispatch) => {
    return {
        FilterList(list) {
            dispatch({ type: "SET_ROUTES", list })
        }
    }
}

Login = withRouter(Login)

export default connect(mapState, mapDispatch)(Login)
